/*
* Copyright (c) 2010 Michael Collins
*
* This file is part of TerraFirma.
*
* TerraFirma is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TerraFirma is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TerraFirma.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LOGIC_THREAD_H
#define LOGIC_THREAD_H

#include "task_thread.h"
#include <lua.hpp>
//#include <SFML/System/Clock.hpp>
#include <message_logic.h>
//#include <boost/timer.hpp>
#include "timer.h"

#define TICK_PERIOD 20 //20 millisecs
//#define TICK_PERIOD_F (1/(1000 * TICK_PERIOD))

namespace engine
{
    /*
    enum hosting {DEDICATED, //Server only
                  CLIENT, //Client only. Server is hosted on another machine
                  LISTEN
                 }; //Server and client hosted at the same time with the same resources
    */

    class logic_thread : public task_thread<Message_Logic>
    {
    public:
        logic_thread();
        ~logic_thread();

        const char* name()
        {
            return "logic_thread";
        }
        void F(const boost::thread::id tid);

        /*Client commands are preceded with Client_**/
        /**Local host is already connected to the host physically, and requests that he be a player in the game
         * This merely begins the player connect process. Handshakes occur automatically afterwards
         */
        bool Client_connect_player();

        /**Local host calls this when he wishes to leave the game
        */
        void Client_disconnect_player();


    protected:
    private:
        bool tick_wait();
        bool timed_wait(unsigned int t, uint8_t command_type);
        void process_message(const Message_Logic& msg);
        void handle_request_event(const Request_Join_Message& msg);
        void handle_player_add(const Player_Connect_Message& msg);
        void handle_player_update(const Player_Update_Message& msg);
        void handle_player_remove(const Player_Disconnect_Message& msg);
        void handle_entity_create(const Entity_Create_Message& msg);
        void handle_control_event(const Player_Control_Message& msg);

        void idle();

        //Helpful wrapper function for running lua files
        int process_lua_file(const char* file);

        //Sends the current state of the game world and all the players to the specified host
        void serialize_gamestate(hostid host);

        lua_State *L;
        bool running;
    };
}
#endif // LOGIC_THREAD_H
